<template>
  <div>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert
        show-icon
        title="注意：只允许为第三级分类设置相关参数"
        type="warning"
        :closable="false"
      >
      </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="row_opt">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            v-model="checkedId"
            :options="cateList"
            :props="cascaderOpt"
            @change="checkedIdChange"
            clearable
          ></el-cascader>
        </el-col>
        <div>&nbsp;</div>
        <!-- 解决el-tabs卡死 -->
        <el-tabs v-model="activePaneName" @tab-clicke="handleTabsClick">
          <el-tab-pane label="静态属性" name="only">
            <!-- 添加按钮 -->
            <el-button type="primary" size="mini" :disabled="isDisabled" @click="addDialogVisible=true"
              >添加静态属性</el-button
            >
            <!-- 静态属性表格 -->
            <el-table :data="onlyParamsList" style="width: 99.9%" stripe border>
              <el-table-column type="expand" width="50">
                <template slot-scope="scope">
                  <!-- 遍历标签 -->
                  <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" closable @close="removeTag(scope.row,index)">{{item}}</el-tag>
                  <!-- 添加标签 -->
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInputRef"
                    size="small"
                    @keyup.enter.native="$event.target.blur(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column type="index" width="50"> </el-table-column>
              <el-table-column prop="attr_name" label="属性名称" width="400">
              </el-table-column>
              <el-table-column label="操作" width="300">
                <template slot-scope="scope">
                  <el-button type="primary" size="mini" class="el-icon-edit" @click="openEditForm(scope.row)"></el-button>
                  <el-button  ton el-button type="danger" size="mini" class="el-icon-delete" @click="deleteParam(scope.row)"></el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="动态参数" name="many">
            <!-- 添加按钮 -->
            <el-button type="primary" size="mini" :disabled="isDisabled" @click="addDialogVisible=true"
              >添加动态参数</el-button
            >
            <!-- 动态参数表格 -->
            <el-table :data="manyParamsList" style="width: 99.9%" stripe border>
              <el-table-column type="expand" width="50">
                <template slot-scope="scope">
                  <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" closable @close="removeTag(scope.row,index)">{{item}}</el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInputRef"
                    size="small"
                    @keyup.enter.native="$event.target.blur(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column type="index" width="50"> </el-table-column>
              <el-table-column prop="attr_name" label="参数名称" width="400">
              </el-table-column>
              <el-table-column label="操作" width="300">
                <template slot-scope="scope">
                  <el-button type="primary" size="mini" class="el-icon-edit" @click="openEditForm(scope.row)"></el-button>
                  <el-button  ton el-button type="danger" size="mini" class="el-icon-delete" @click="deleteParam(scope.row)"></el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-row>
    </el-card>

    <!-- 添加动态参数或静态属性 -->
    <el-dialog
      :title="addText"
      :visible.sync="addDialogVisible"
      width="50%"
      @closed="closedAdd"
    >
      <!-- 带验证的表单 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item :label="labelText" prop="attr_name" label-width="120px">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 提交按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParamsForm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改动态参数或静态属性 -->
    <el-dialog
      :title="editText"
      :visible.sync="editDialogVisible"
      width="50%"
      @closed="closedEdit"
    >
      <!-- 带验证的表单 -->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item :label="labelText" prop="attr_name" label-width="120px">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 提交按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParamsForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Params',
  created() {
    // 请求分类列表
    this.getCateList()
  },
  data() {
    return {
      // 分类列表
      cateList: [],
      // 级联选择器配置
      cascaderOpt: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      // 选中的id
      checkedId: [],
      // 选中的参数标签
      activePaneName: 'only',
      // 静态属性列表
      onlyParamsList: [],
      // 动态参数列表
      manyParamsList: [],
      // 添加对话框
      addDialogVisible:false,
      // 添加表单
      addForm:{
        attr_name:'',
      },
      // 添加表单规则
      addFormRules:{
        attr_name:[
        { required: true, message: '请输入活动名称', trigger: 'blur' },
            { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ]
      },
      // 编辑对话框
      editDialogVisible:false,
      // 编辑表单
      editForm:{
        attr_name:'',
        attr_id:null
      },
      // 编辑表单规则
      editFormRules:{
        attr_name:[
        { required: true, message: '请输入活动名称', trigger: 'blur' },
            { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ]
      },
      // 添加标签输入框/按钮的显示
      inputVisible:false,
      // 添加输入框的值
      inputValue:''
    }
  },
  methods: {
    // 请求分类列表
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200)
        return this.$message.error('请求分类列表失败！')
      this.cateList = res.data
    },
    // 选项更改
    checkedIdChange() {
      if (this.checkedId.length !== 3) {
        this.checkedId = []
        this.onlyParamsList=[]
        this.manyParamsList=[]
        return
      }
      this.sendQuery()
    },
    // 发送静态属性/动态参数请求
    async sendQuery(){
      // 请求参数
      const { data: res1 } = await this.$http.get(
        'categories/' + this.checkedId[2] + '/attributes',
        { params: { sel: 'only' } }
      )
      if (res1.meta.status !== 200)
        return this.$message.error('请求失败！')
      res1.data.forEach(item=>{
        item.attr_vals=item.attr_vals?item.attr_vals.split(' '):[]
        item.inputVisible=false
        item.inputValue=''
      })
      this.onlyParamsList = res1.data
      const { data: res2 } = await this.$http.get(
        'categories/' + this.checkedId[2] + '/attributes',
        { params: { sel: 'many' } }
      )
      if (res2.meta.status !== 200)
        return this.$message.error('请求失败！')
      res2.data.forEach(item=>{
        item.attr_vals=item.attr_vals?item.attr_vals.split(' '):[]
        item.inputVisible=false
        item.inputValue=''
      })
        this.manyParamsList = res2.data
    },
    // 标签更改
    handleTabsClick() {},
    // 提交添加
    addParamsForm(){
      this.$refs.addFormRef.validate(async valid=>{
        if(valid){
          const{data:res}=await this.$http.post(`categories/${this.checkedId[2]}/attributes`,{
            attr_name:this.addForm.attr_name,
            attr_sel:this.activePaneName
          })
          if(res.meta.status!==201) return this.$message.error('添加失败！')
          this.$message.success('添加成功！')
          this.addDialogVisible=false
          this.sendQuery()
        }
      })
    },
    // 关闭添加对话框
    closedAdd(){
      this.$refs.addFormRef.resetFields()
    },
    // 关闭编辑对话框
    closedEdit(){
      this.$refs.editFormRef.resetFields()
    },
    // 打开编辑表单
    openEditForm(item){
      this.editForm.attr_name=item.attr_name
      this.editForm.attr_id=item.attr_id
      this.editDialogVisible=true
    },
    // 提交编辑表单
    editParamsForm(){
      this.$refs.editFormRef.validate(async valid=>{
        if(valid){
          const {data:res}=await this.$http.put(`categories/${this.checkedId[2]}/attributes/${this.editForm.attr_id}`,{
            attr_name:this.editForm.attr_name,attr_sel:this.activePaneName
          })
          if(res.meta.status!==200) return this.$message.error('修改数据失败')
          this.$message.success('修改数据成功')
          this.sendQuery()
          this.editDialogVisible=false
        }
      })
    },
    // 删除静态属性/动态参数
    deleteParam(item){
      this.$confirm('此操作将永久删除该'+this.labelText.substr(0,4)+'是否继续?','提示',{
        confirmButtonText:'确定',
        cancelButtonText:'取消',
        type:'warning'
      }).then(async()=>{
        const{data:res}=await this.$http.delete(`categories/${this.checkedId[2]}/attributes/${item.attr_id}`)
        if(res.meta.status!==200) this.$message.error('删除失败')
        this.$message.success('删除成功')
        this.sendQuery()
      }).catch(()=>{
        this.$message.info('取消删除')
      })
    },
    // 添加输入框输入完毕
    handleInputConfirm(row){
      if(!row.inputValue.trim()){
        this.$message.error('添加不能为空！')
        row.inputValue=''
        row.inputVisible=false 
        return 
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue=''
      this.updateTag(row)
      row.inputVisible=false 
    },
    // 删除标签
    removeTag(row,id){
      row.attr_vals.splice(id,1)
      this.updateTag(row)
    },
    // 标签内数据修改
    async updateTag(row){
      const {data:res}=await this.$http.put(`categories/${this.checkedId[2]}/attributes/${row.attr_id}`,{
        attr_name:row.attr_name,attr_sel:row.attr_sel,attr_vals:row.attr_vals.join(' ')
      })
      if(res.meta.status!==200) return this.$message.error('修改数据失败')
      this.$message.success('修改数据成功')
    },
    // 点击添加标签按钮
    showInput(row){
      row.inputVisible=true
      this.$nextTick(()=>{
        this.$refs.saveTagInputRef.$refs.input.focus()
      })
    }
  },
  computed: {
    // 是否禁用添加参数按钮
    isDisabled() {
      return this.checkedId.length !== 3
    },
    // 添加属性标题
    addText(){
      if(this.activePaneName==='only') return '添加静态属性'
      else return '添加动态参数'
    },
    // 属性标题
    labelText(){
      if(this.activePaneName==='only') return '静态属性名称'
      else return '动态参数名称'
    },
    // 编辑内容标题
    editText(){
      if(this.activePaneName==='only') return '修改静态属性'
      else return '修改动态参数'
    }
  },
}
</script>

<style lang="less" scoped>
.row_opt {
  margin-top: 15px;
}
.el-cascader {
  width: 70%;
}
.el-tag{
  margin: 10px;
}
.input-new-tag{
  width: 120px;
}
</style>